#include "main.h"
#include "heartbeat.h"
#include "Switch.h"
#include "user_led.h"
#include "Model_info.h"
//#include "iwdg.h"
//#include "tim.h"
#include "user_led.h"
//#include "adc.h"

void Heartbeat_Send(void);
void Init_Heartbeat(Heartbeat_TCB_t *tcb,uint16_t timeout);
void Set_LED_Link(bool status);
void Heartbeat_Send_Response(void);
Heartbeat_TCB_t heartbeat_handle;

uint8_t led_link=0;
bool     send_flag=false;
void Enable_LED_Link(void)
{
	led_link=1;
}
void DisEnable_LED_Stop(void)
{
	led_link=0;
}
uint32_t Get_RNG()
{
	uint16_t rng_value;
	return Get_lora_Random();
	//srand(Get_RNG_ADC());
	//rng_value=rand();
}

void LED_Link_Run()
{
	if(led_link)
	{
		HAL_GPIO_WritePin(LED_LINK_GPIO_Port, LED_LINK_Pin, GPIO_PIN_SET);
	}
	else
	{
		HAL_GPIO_TogglePin(LED_LINK_GPIO_Port,LED_LINK_Pin);
	}
}
void Strat_SendHeart(uint16_t time)
{
	if(!send_flag)
	{
		heartbeat_handle.time=0;
		heartbeat_handle.time_wait=time;
		send_flag=true;
	}
}
uint16_t rng_time=0;
/**********************
*
**********************/
void Heardbeat_Init(void)
{
	Init_Heartbeat(&heartbeat_handle,10000);
	HAL_Delay(500);
}
/// @brief 心跳线程入口
/// @param  
void Heartbeat_Loop(uint8_t ms)
{
	heartbeat_handle.time+=ms;
	if(heartbeat_handle.loop_time<100)
	{
		heartbeat_handle.loop_time+=ms;
		return;
	}
	heartbeat_handle.loop_time=0;
	if(heartbeat_handle.time>heartbeat_handle.timeout)
	{
		heartbeat_handle.status=false;
	}
  if(heartbeat_handle.recive)
	{
		heartbeat_handle.status=true;
		heartbeat_handle.recive=false;
		heartbeat_handle.time=0;
			//ReSetOverTime();
	}
	Set_LED_Link(heartbeat_handle.status);
	LED_Link_Run();
		//HAL_IWDG_Refresh(&hiwdg);
}
/// @brief 设置 连接指示灯状态
/// @param  
void Set_LED_Link(bool status)
{
	if(status)   //连接正常
	{
		Enable_LED_Link();
	}
	else        //断开连接
	{
		DisEnable_LED_Stop();
	}
}

/// @brief 初始化心跳
/// @param  
void Init_Heartbeat(Heartbeat_TCB_t *tcb,uint16_t timeout)
{
	tcb->recive=false;
	tcb->status=false;
	tcb->time=0;
	tcb->timeout=timeout;
}
void Updata_Heartbeat_Status(void)
{
		heartbeat_handle.recive=true;
}
/// @brief 接收心跳
/// @param  
void Heartbeat_Receive(void)
{
	Heartbeat_Send_Response();
}

/// @brief 发送心跳响应
/// @param  
void Heartbeat_Send_Response(void)
{
	Switch_Protocol sw;
	sw.id=model_info_handle.general_info.SN;
	sw.status.relay_out=User_Get_Relay_status();
	sw.status.sw_in=User_Get_Sw_status();
	sw.type=SW_Heartbeat_Response;
	User_LoRaSend_Data((uint8_t *)&sw,sizeof(Switch_Protocol));
}
/// @brief 发送心跳
/// @param  
void Heartbeat_Send(void)
{
	Switch_Protocol sw;
	sw.id=model_info_handle.general_info.SN;
	sw.status.relay_out=User_Get_Relay_status();
	sw.status.sw_in=User_Get_Sw_status();
	sw.type=SW_Heartbeat;
	User_LoRaSend_Data((uint8_t *)&sw,sizeof(Switch_Protocol));
}